<?php

namespace Largezhou\Admin\Traits;

use Closure;

trait TreeOptions
{
    /**
     * 把所有数据生成按父子关系嵌套的数组
     *
     * @param null         $items 所有数据
     * @param int          $parentId 父级id
     * @param Closure|null $dataCallback 处理数据的回调函数$dataCallback($item)
     *
     * @return array
     */
    public static function makeTreeOptions($items = null, $parentId = 0, Closure $dataCallback = null)
    {
        $data = [];

        if (is_null($items)) {
            $items = static::getAllItems();
        }

        foreach ($items as $item) {
            if ($item[static::parentColumn()] == $parentId) {
                $children = static::makeTreeOptions($items, $item['id'], $dataCallback);

                $node = is_callable($dataCallback)
                    ? call_user_func($dataCallback, $item)
                    : $item;

                if (count($children) > 0) {
                    $node['children'] = $children;
                }

                $data[] = $node;
            }
        }

        return $data;
    }

    public static function getAllItems()
    {
        return static::orderBy(static::orderColumn())->get()->toArray();
    }

    protected static function titleColumn()
    {
        return 'title';
    }

    protected static function parentColumn()
    {
        return 'parent_id';
    }

    protected static function orderColumn()
    {
        return 'order';
    }
}
